//
//  YSDownLoadManager.m
//  YSDownLoader_Example
//
//  Created by Kyson on 2018/12/4.
//  Copyright © 2018 kysonyangs. All rights reserved.
//

#import "YSDownLoadManager.h"
#import "NSString+YSDownloader.h"

@interface YSDownLoadManager () <NSCopying, NSMutableCopying>

@property (nonatomic, strong) NSMutableDictionary <NSString *, YSDownLoader *>*downLoadInfo;

@end

@implementation YSDownLoadManager

// 绝对的单例: 无论通过什么样的方式, 创建, 都是一个对象
// 非绝对的单例
static YSDownLoadManager *_shareInstance;
+ (instancetype)shareInstance {
    if (!_shareInstance) {
        _shareInstance = [[self alloc] init];
    }
    return _shareInstance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    if (!_shareInstance) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _shareInstance = [super allocWithZone:zone];
        });
    }
    return _shareInstance;
}

- (id)copyWithZone:(NSZone *)zone {
    return _shareInstance;
}

- (id)mutableCopyWithZone:(NSZone *)zone {
    return _shareInstance;
}

- (NSMutableDictionary<NSString *,YSDownLoader *> *)downLoadInfo {
    if (!_downLoadInfo) {
        _downLoadInfo = [NSMutableDictionary dictionary];
    }
    return _downLoadInfo;
}

- (void)downLoadWithURL:(NSURL *)url downLoadInfo:(DownLoadInfoType)downLoadBlock progress:(ProgressBlockType)progressBlock success:(SuccessBlockType)successBlock failed:(FailedBlockType)failBlock {
    // 1. url
    NSString *urlMD5 = [url.absoluteString md5];
    
    // 2. 根据 urlMD5 , 查找相应的下载器
    YSDownLoader *downLoader = self.downLoadInfo[urlMD5];
    if (downLoader == nil) {
        downLoader = [[YSDownLoader alloc] init];
        self.downLoadInfo[urlMD5] = downLoader;
    }
    
    __weak typeof(self) weakSelf = self;
    [downLoader downLoader:url downLoadInfo:downLoadBlock progress:progressBlock success:^(NSString *filePath) {
        [weakSelf.downLoadInfo removeObjectForKey:urlMD5];
        // 拦截block
        successBlock(filePath);
    } failed:failBlock];
    
    // 下载完成之后, 移除下载器
    //
}

- (void)pauseWithURL:(NSURL *)url {
    NSString *md5 = [url.absoluteString md5];
    YSDownLoader *downLoader = self.downLoadInfo[md5];
    [downLoader pauseCurrentTask];
}

- (void)resumeWithURL:(NSURL *)url {
    NSString *urlMD5 = [url.absoluteString md5];
    YSDownLoader *downLoader = self.downLoadInfo[urlMD5];
    [downLoader resumeCurrentTask];
}
- (void)cancelWithURL:(NSURL *)url {
    NSString *urlMD5 = [url.absoluteString md5];
    YSDownLoader *downLoader = self.downLoadInfo[urlMD5];
    [downLoader cacelCurrentTask];    
}

- (void)pauseAll {
    [self.downLoadInfo.allValues makeObjectsPerformSelector:@selector(pauseCurrentTask)];
}

- (void)resumeAll {
    [self.downLoadInfo.allValues makeObjectsPerformSelector:@selector(resumeCurrentTask)];
}

@end
